package com.my.okhttps.utils;

import cn.hutool.core.util.StrUtil;
import org.apache.commons.io.IOUtils;
import org.apache.tomcat.util.codec.binary.Base64;

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.*;

/**
 * http签名
 */
public class EsbUtil {
    /**
     * 签名
     */
    public static String sign(String source,String privateKeyPath) throws Exception {
        //读取解析私钥（解析完成的PrivateKey对象建议缓存起来）
        InputStream in = new FileInputStream(privateKeyPath);
        PrivateKey privateKey = null;
        String sign = null;
        try {
            byte[] keyBytes = IOUtils.toByteArray(in);
            byte[] encodedKey = Base64.decodeBase64(keyBytes);
            KeySpec keySpec = new PKCS8EncodedKeySpec(encodedKey);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            privateKey = keyFactory.generatePrivate(keySpec);
        } finally {
            IOUtils.closeQuietly(in);
        }
        if (privateKey != null) {
            //签名
            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initSign(privateKey);
            signature.update(source.getBytes());
            byte[] signed = signature.sign();
            //取base64， 得到签名串
            sign = Base64.encodeBase64String(signed);
        }
        return sign;
    }

    public static String signKey(String source,String privateKeyString) throws Exception {
        //读取解析私钥（解析完成的PrivateKey对象建议缓存起来）
//        InputStream in = new FileInputStream(privateKeyPath);
        PrivateKey privateKey = null;
        String sign = null;
//        try {
//            byte[] keyBytes = IOUtils.toByteArray(in);
            byte[] encodedKey = Base64.decodeBase64(privateKeyString.getBytes());
            KeySpec keySpec = new PKCS8EncodedKeySpec(encodedKey);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            privateKey = keyFactory.generatePrivate(keySpec);
//        }
//        finally {
//            IOUtils.closeQuietly(in);
//        }
        if (privateKey != null) {
            //签名
            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initSign(privateKey);
            signature.update(source.getBytes());
            byte[] signed = signature.sign();
            //取base64， 得到签名串
            sign = Base64.encodeBase64String(signed);
        }
        return sign;
    }
    /**
     * 生成源串
     * @param params
     * @return
     */
    public static String generateSignSource(Map params) {
        Set<String> keySet = params.keySet();
        List<String> keys = new ArrayList<>();
        for (String key : keySet) {
            if (params.get(key) != null && StrUtil.isNotBlank(params.get(key).toString())) {
                keys.add(key);
            }
        }
        Collections.sort(keys);
        StringBuilder builder = new StringBuilder();
        for (int i = 0, size = keys.size(); i < size; i++) {
            String key = keys.get(i);
            Object value = params.get(key);
            builder.append(key);
            builder.append("=");
            builder.append(value);
            //拼接时， 不包括最后一个&字符
            if (i != size - 1) {
                builder.append("&");
            }
        }
        return builder.toString();
    }
}
